//
//  PluginTestListViewController.m
//  PCDBankSix
//
//  Created by APPLE on 2023/8/17.
//

#import "PluginTestListViewController.h"
#import "PCDDataBaseModel.h"
#import "PCDLoginModel.h"
#import <ExBankCardSDK/ExBankCardSDK.h>
#import "PCDLocateModel.h"
#import "PCDFaceRecoManager.h"
#import "ESBankDevice.h"
#import "PCDBluetoothManager.h"
#import "YTOpenFIleAlertView.h"
#import "DataListSelectedView.h"
#import "PCDApiKeyBoard.h"
#import "YTGestureViewController.h"
#import "PCDCSTSkinListViewController.h"
#import "YTChangeBTPinViewController.h"

@interface PluginTestListViewController ()<UITableViewDelegate,UITableViewDataSource, CBCentralManagerDelegate, BRDateResultDelegate>
/**蓝牙管理类*/
@property (nonatomic, strong) CBCentralManager * cbCentralManager;

@property(nonatomic,strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *listArray;

@end

@implementation PluginTestListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"插件调试页面";
    self.listArray = @[@"插件测试页",
                       @"跳转首页",
                       @"更改登录状态",
                       @"打电话",
                       @"手势修改",
                       @"ocr银行卡识别",
                       @"身份证识别",
                       @"皮肤",
                       @"获取当前定位信息",
                       @"获取蓝牙",
                       @"人脸识别",
                       @"营业执照",
                       @"PDF页面",
                       @"PDF弹窗",
                       @"数据选择器",
                       @"跳转手势验证",
                       @"通讯录",
                       @"修改飞天蓝牙key",
                       @"修改文鼎蓝牙key",
    ];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero];
    self.tableView.bounces = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    
    self.tableView.showsVerticalScrollIndicator= NO;
    self.tableView.showsHorizontalScrollIndicator= NO;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(self.navigationBarHeight);
        make.bottom.mas_equalTo(self.view);
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 60;
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SortMenuTableViewCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SortMenuTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSString *title = self.listArray[indexPath.row];
    cell.textLabel.text = title;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    PCDContext *context = [PCDContext new];
    context.viewController = self;
    [self handler:nil andContext:context type:indexPath.row];
}

- (void)handler:(id)data andContext:(PCDContext *)context type:(NSInteger)type{
    PCDBankWebViewController *view = context.viewController;
    if (type == 0) {
        NSMutableDictionary *paramsDic = [NSMutableDictionary dictionaryWithDictionary:@{
                    @"url":@"https://124.239.138.229:19999/test1"}];
        PCDBankWebViewController *viewController = (PCDBankWebViewController *)[[CTMediator sharedInstance] CTMediatorH5ContainerViewController:paramsDic];
        viewController.title = @"插件测试";
        [view.navigationController pushViewController:viewController animated:YES];
    } else if (type == 1) {
        //回到首页
        view.tabBarViewController.selectedIndex = 0;
        [view.navigationController popToRootViewControllerAnimated:YES];
    }else if (type == 2) {
        //更改登录状态
        //退出登录
        [PCDUtil saveLoginSession:nil];
        //清空内存缓存信息
        [[PCDDataBaseModel shareModel].memoryStorage removeAllObjects];
        //发退出登录接口
        [[PCDLoginModel shareInstance] loginOut:^(BOOL success, NSString * _Nonnull strMsg) {
            [PCDUtil saveLoginSession:nil];
        }];
    }else if (type == 3) {
        //打电话
        NSString *phoneNo = @"15230839232";
        
        if (phoneNo) {
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNo]];
            [[UIApplication sharedApplication]openURL:url];
        }else{
            [PCDUtil toastMessage:@"号码为空！"];
        }
    }else if (type == 4) {
        //手势修改
        YTGestureViewController *loginView = [[YTGestureViewController alloc] initWithNibName:@"YTGestureViewController" bundle:nil];
        loginView.settingType = 1;
        loginView.isFromWeb = YES;
        [loginView setLoginCompleteBlock:^(BOOL isSuccess, id  _Nonnull session) {
            if (isSuccess) {
            } else {
                if ([session isKindOfClass:[NSString class]]) {
                    
                }
            }
        }];
        
        [view.navigationController pushViewController:loginView animated:YES];
    }else if (type == 5) {
        //银行卡识别
        EXOCRBankRecoManager *manager = [EXOCRBankRecoManager sharedManager:view];
        [manager setDisplayLogo:NO];
        [manager setScanTips:@"请将银行卡正面放入框内"];
        [manager recoBankFromStreamOnCompleted:^(int statusCode, EXOCRBankCardInfo *bankInfo) {
        } OnCanceled:^(int statusCode) {
        } OnFailed:^(int statusCode, UIImage *failImg) {
        }];
    }else if (type == 6) {
        //营业执照识别
        [EXOCRCardEngineManager initEngine];
        BOOL bShouldFront = YES;
        
        EXOCRIDCardRecoManager *manager = [EXOCRIDCardRecoManager sharedManager:view];
        [manager setDisplayLogo:NO];
        [manager setCustomScanView:nil];
        [manager displayScanViewControllerByPresent:YES];

        __weak typeof(self) weakSelf = self;
        [manager recoIDCardFromStreamWithSide:bShouldFront OnCompleted:^(int statusCode, EXOCRIDCardInfo *idInfo) {
        } OnCanceled:^(int statusCode) {
        } OnFailed:^(int statusCode, UIImage *recoImg) {
        }];
    }else if (type == 7) {
        //皮肤
        PCDCSTSkinListViewController *skinListVC = [PCDCSTSkinListViewController new];
        [view.navigationController pushViewController:skinListVC animated:YES];
    }else if (type == 8) {
        //获取定位信息
        [[PCDLocateModel shareLocateInstance] baidu_locateWithCompletion:^(BMKLocation * _Nullable location, NSDictionary * _Nonnull locations, NSError * _Nonnull error) {
            if (error) {
//                NSString *strJson = [@{@"status":@"false",@"latitude":PCD_DEFAULT_LATITUDE ,@"longitude": PCD_DEFAULT_LONGTITUDE,@"province":@"河北省",@"district":@"",@"address":@"",@"city":PCD_DEFAULT_CITY} JSONRepresentation];
            }else{
                NSString *message = [NSString stringWithFormat:@"%@%@%@%@%@",locations[@"Province"],locations[@"City"],locations[@"District"],locations[@"Street"],locations[@"StreetNumber"]];

                NSString *locationStatus = @"true";
                if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized)) {
                    
                    //定位功能可用
                    locationStatus = @"true";
                    
                }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
            
                    //定位不能用
                    locationStatus = @"false";
                }
                NSString *strJson = [@{@"status":locationStatus,
                                       @"latitude":[PCDUtil safeString:locations[@"Latitude"]],
                                       @"longitude": [PCDUtil safeString:locations[@"Longitude"]],
                                       @"country":[PCDUtil safeString:locations[@"Country"]],
                                       @"province":[PCDUtil safeString:locations[@"Province"]],
                                       @"city":[PCDUtil safeString:locations[@"City"]],
                                       @"district":[PCDUtil safeString:locations[@"District"]],
                                       @"address":message
                                     } JSONRepresentation];
            }

        }];
    }else if (type == 9) {
        //获取蓝牙
        
        _cbCentralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
        
    }else if (type == 10) {
        //人脸识别
        [[PCDFaceRecoManager shareInstance] startFaceWithVC:view Type:veryFaceTypeFromWeb showTips:@"我行采集人脸信息仅用于登录、转账等实时交易场景中对您的身份进行核实" resultBlock:^(BOOL resultStatus, id  _Nullable resultInfo) {
            if (resultStatus) {
                
            }else {
                [PCDUtil toastMessage:resultInfo];
            }
        }];
    }else if (type == 11) {
        //营业执照
        __weak typeof(self) weakSelf = self;
        
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
            authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先去设置中开启相机权限" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAct = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:cancelAct];
            UIAlertAction *settingAct = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication]canOpenURL:url]) {
                    [[UIApplication sharedApplication]openURL:url];
                }
            }];
            [alertController addAction:settingAct];
            [view.navigationController presentViewController:alertController animated:YES completion:nil];
            
            return;
        }
        [self addPicEvent:nil type:UIImagePickerControllerSourceTypeCamera responseBlock: ^(id responseData)
         {
             
         }];
        
    }else if (type == 12) {
        //PDF页面
//        NSMutableDictionary *paramsDic = [NSMutableDictionary dictionaryWithDictionary:@{
//                    @"url":[[NSBundle mainBundle] pathForResource:@"PDF" ofType:@"pdf"]}];
//        PCDBankWebViewController *viewController = (PCDBankWebViewController *)[[CTMediator sharedInstance] CTMediatorH5ContainerViewController:paramsDic];
//        viewController.title = @"在线文件展示";
//        [view.navigationController pushViewController:viewController animated:YES];
        
        NSDictionary  *params = @{@"url":@"", @"extraData":@"agreement"};
        
        PCDBankWebViewController *viewController = (PCDBankWebViewController *)[PCDPageViewMangeGet() creatCacheWebController:params View:view Status:NO];
        viewController.title = @"隐私协议";
        [viewController.bankWebView reload];
        viewController.isAgreement = YES;
        viewController.agreeBtnTitle = @"同意";
        viewController.maxSeconds = 5;
        __weak typeof(self) tempSelf = self;
        [viewController setBackBlock:^(BOOL status) {
            if (status) {
                
            }
        }];
        [view.navigationController pushViewController:viewController animated:YES];
        
    }else if (type == 13) {
        //PDF弹窗
        YTOpenFIleAlertView *alertView = [[YTOpenFIleAlertView alloc]initWithTitle:@"提示"
                                                                           fileUrl:
//                                          [[NSBundle mainBundle] pathForResource:@"PDF" ofType:@"pdf"]
                                            [[NSBundle mainBundle] pathForResource:@"Word" ofType:@"docx"]
            //                            [[NSBundle mainBundle] pathForResource:@"Excel" ofType:@"xlsx"]
                                                                          readType:0
                                                                    firstItemTitle:@"否"
                                                                   secondItemTitle:@"是"
                                                                       cancleBlock:^{
            
        }
                                                                      confirmBlock:^{
            
        }];
        [alertView show];
    }else if (type == 14) {
        //数据选择器
        __weak typeof(self) weakSelf = self;
        DataListSelectedView *selectedView = [[DataListSelectedView alloc]initWithSelectValue:@"你好" dataArray:@[@"你好", @"我好", @"他好", @"大家好", @"我们好"]];
        selectedView.delegate = self;
        [selectedView showWithAnimation:YES];
    }else if (type == 15) {
        //跳转手势验证
        
    }else if (type == 16) {
        //
        __weak typeof(self) tempSelf = self;
        PCContactRelay relay =^(NSString * name, NSString * phoneNumber, BOOL isCancel){
            //这里将isCancel也回调出来，是为了处理特殊情况，比如重新设置状态栏颜色
            if (!isCancel) {
                
            }else{
                
            }
        };
        if (@available(iOS 9,*)) {
            CNContactPickerViewController *picker = [CNContactPickerViewController pickerWithParentController:view completion:relay];
            [picker show];
        }else{
            ABPeoplePickerNavigationController *picker =[ABPeoplePickerNavigationController pickerWithParentController:view completion:relay];
            [picker show];
        }
    }else if (type == 17) {
        YTChangeBTPinViewController * vc = [[YTChangeBTPinViewController alloc]init];
        vc.SN = @"HBBank7100000019";
        vc.modifyResultBlock = ^(BOOL success, NSString * _Nonnull info) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!success){
//                                evaluateJavaScriptOnMainThread(self, failkcallBack, result.JSONRepresentation);
                    return;
                }
                [view.navigationController popViewControllerAnimated:YES];
//                            evaluateJavaScriptOnMainThread(self, callBack, result.JSONRepresentation);
            });
        };
        [view.navigationController pushViewController:vc animated:YES];
        
        
    }else if (type == 18) {
        __weak typeof(self) tempSelf = self;
        [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(wd_didDisconnectUkey:) name:ESIBankDeviceDidDisconnect object:nil];
        [self.view showHBWaitWithTitle:@"蓝牙key连接中..." isFullScreen:YES];
        [PCDBluetoothManager.shareManager connectUKeyWithSN:@"HBBank7290000170" connectBlock:^(BOOL result, id  _Nonnull model) {
            [tempSelf.view showHBWait:NO isFullScreen:YES];
            if (result) {///连接成功
                YTBluetoothAuthHandle.sharedInstance.ukeyType = YTUkeyConnectType_WD;
                [tempSelf.view showHBWait:YES isFullScreen:YES];
                [PCDBluetoothManager.shareManager UIchangePINCodeWithCompleteBlock:^(BOOL result, NSString * _Nonnull errorString) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [tempSelf.view showHBWait:NO isFullScreen:YES];
                        [PCDUtil toastMessage:errorString];
                        if (result) {
//                            evaluateJavaScriptOnMainThread(wself, wself.strCallback, @"");
                        }else {
//                            evaluateJavaScriptOnMainThread(wself, wself.failCallback, @"");
                        }
                    });
                }];
            } else {/// 连接失败
                dispatch_async(dispatch_get_main_queue(), ^{
//                    evaluateJavaScriptOnMainThread(wself, wself.failCallback, @"");
                });
            }
        }];
    }
}

- (void) addPicEvent:(NSDictionary *)parma type:(UIImagePickerControllerSourceType)picType  responseBlock:(WVJBResponseCallback)responseCallback {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        return;
    }
    
    UIImagePickerControllerSourceType sourceType = picType;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = sourceType;
    picker.completionBlock = ^(UIImagePickerController *pickerController, NSDictionary *info){
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        NSData * imageData1 = [self compressOriginalImage:image toMaxDataSizeKBytes:100 * 1024];
        NSString *imageBase64Str = [imageData base64EncodedStringWithOptions:0];
        NSDictionary *params = @{@"imageBase64Str":imageBase64Str};
        
        [pickerController dismissViewControllerAnimated:YES completion:NULL];
    };
    
    picker.cancelBlock = ^(UIImagePickerController *picker){
        [picker dismissViewControllerAnimated:YES completion:NULL];
    };
    
    [self presentViewController:picker animated:YES completion:NULL];
}

/*!
 *  @brief 使图片压缩后刚好小于指定大小
 *
 *  @param image 当前要压缩的图 maxLength 压缩后的大小
 *
 *  @return 图片对象
 */
//图片质量压缩到某一范围内，如果后面用到多，可以抽成分类或者工具类,这里压缩递减比二分的运行时间长，二分可以限制下限。
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)maxLength{
    //首先判断原图大小是否在要求内，如果满足要求则不进行压缩，over
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return data;
    //压处理，
    //这里 压缩比 采用二分法进行处理，6次二分后的最小压缩比是0.015625，已经够小了
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) {
        return data;
    }
    
    //缩处理
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //获取处理后图片的大小
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    return data;
}


#pragma mark - CBCentralManagerDelegate
-(void)centralManagerDidUpdateState:(CBCentralManager *)central {
    switch (central.state) {
            case CBManagerStateUnknown:
            
                break;
            case CBManagerStateResetting:
            
                break;
            case CBManagerStateUnsupported:
                //不支持蓝牙
                
                break;
            case CBManagerStateUnauthorized:
                //未获取权限
                break;
            case CBManagerStatePoweredOff:
                //蓝牙关
//                [self showBluetoothDisabledMessage];
            [PCDUtil toastMessage:@"蓝牙关了"];
                break;
            case CBManagerStatePoweredOn:
                //蓝牙开
                //MARK:扫描周围外设（支持蓝牙）
            break;
        }
    
        CBPeripheralManagerAuthorizationStatus authStatus = [CBPeripheralManager authorizationStatus];
//        self.bluetoothAuthBlock(authStatus == CBPeripheralManagerAuthorizationStatusAuthorized, authStatus);
}

-(void)getDatePickerResult:(NSString *)date {
    NSDictionary *dict = @{@"text":date};
    
}

- (void)wd_didDisconnectUkey:(NSNotification *)noti{
    Weakify(self);
    [PCDUtil toastMessage:@"蓝牙key已经断开连接"];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
